package com.haohe.wx.util;

import java.util.Calendar;
import java.util.Date;

import java.text.SimpleDateFormat;

import com.sinosoft.transverse.common.DateAndTime;

/**
 * 
 * @Title 日期处理常用类
 * @Description TODO
 * @author liming.zhao@haohedata.com
 * @date 2015-7-21 
 * @time 下午3:35:03
 */
public class DateUtil {
	
	private static final java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	/**
	 * 根据生日计算年龄
	 * @param birthday
	 * @return
	 * @throws Exception
	 */
    public static int calAge(Date birthday)throws Exception{
    	try{
    		String date = sdf.format(birthday);
    		String nowDate = DateAndTime.getCurrentDate();
    		int result = DateAndTime.dateDiff(DateAndTime.DATATYPE_YEAR, date, nowDate);
    		String temp = DateAndTime.dateAdd(DateAndTime.DATATYPE_YEAR, date, result);
    		if (DateAndTime.dateDiff(DateAndTime.DATATYPE_DAY, temp, nowDate) <= 0) {
    			result--;
    		}
    		return result;
    	}catch(Exception ex){
    		throw ex;
    	}
    }
    
    /**
     * 年龄计算  核心算法
     */
    public static int calAge(Date birthday, String type) throws Exception {
		try {
			String currDate = DateAndTime.getCurrentDate();
			String date = sdf.format(birthday);
			if ("D".equalsIgnoreCase(type)) {
				return DateAndTime.dateDiff(DateAndTime.DATATYPE_DAY, date, currDate);
			} else if ("M".equalsIgnoreCase(type)) {
				int result = DateAndTime.dateDiff(DateAndTime.DATATYPE_MONTH, date, currDate);
				String temp = DateAndTime.dateAdd(DateAndTime.DATATYPE_MONTH, date, result);
				if (DateAndTime.dateDiff(DateAndTime.DATATYPE_DAY, temp, currDate) <= 0) {
					result--;
				}
				return result;
			} else {
				int result = DateAndTime.dateDiff(DateAndTime.DATATYPE_YEAR, date, currDate);
				String temp = DateAndTime.dateAdd(DateAndTime.DATATYPE_YEAR, date, result);
				if (DateAndTime.dateDiff(DateAndTime.DATATYPE_DAY, temp, currDate) <= 0) {
					result--;
				}
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
    /**
     * 比较当前日期是否在指定日期之内
     * @param checkDate 指定日期
	 * @return true:当前日期在指定日期之内,false:当前日期在指定日期之外
	 * @throws Exception
     */
    public static boolean compareNowDate(String checkDate) throws Exception {
    	try {
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		Calendar c = Calendar.getInstance();
    		c.setTime(sdf.parse(checkDate));
    		long checkTime = c.getTimeInMillis();
    		long now = new Date().getTime();
    		if(now - checkTime >= 0){
    			return true;
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    		throw e;
    	}
    	return false;
    }
    
    public static Long getCurrentTime(){
    	return System.currentTimeMillis();
    }
}
